package com.gogowan.agroenterprise.newview;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.RetrofitUtil.GsonUtil;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.OrderEditRequest;
import com.gogowan.agroenterprise.model.ReplaceCodeRequest;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.utils.SystemBroadCast;
import com.gogowan.agroenterprise.utils.Utils;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class New_HM_Activity extends BaseActivity {
    @BindView(R.id.hm_close)
    TextView hmClose;
    @BindView(R.id.hm_old_ed)
    EditText hmOldEd;
    @BindView(R.id.hm_old_im)
    CheckBox hmOldIm;
    @BindView(R.id.hm_new_ed)
    EditText hmNewEd;
    @BindView(R.id.hm_new_im)
    CheckBox hmNewIm;
    @BindView(R.id.hm_sub_tv)
    TextView hmSubTv;
    private boolean isNew=false;
    private ProgressDialog progressDialog;
    private LoginResultInfo loginResultInfo;
    private long enterpriseId;
    @Override
    public void onResume() {
        isVisible = true;
        super.onResume();
        //registerReceiver(new String[] { getString(R.string.SCAN_ACTION) });
        registerIDataReceiver(new String[] { getString(R.string.SCAN_IDATA_ACTION) });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hm);
        ButterKnife.bind(this);
        hmOldIm.performClick();
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
        enterpriseId = prefs.getLong("enterpriseId", 0);
        prefs = getSharedPreferences("LoginINfo", 0);
        String string = prefs.getString("saveLoginInfo", "");
        loginResultInfo = (LoginResultInfo) Utils.fromJSON(
                string, LoginResultInfo.class);
        initScanView(new SystemBroadCast.ScanResultListener() {
            @Override
            public void OnResult(String CodeString) {
                if (CodeString!=null){
                    if (!isNew){
                        hmOldEd.setText(CodeString+"");
                    }else {
                        hmNewEd.setText(CodeString+"");
                    }
                }else {
                    showToast(getString(R.string.scan_timeout_warn), 0);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        isVisible = false;
        super.onPause();
    }
    @OnClick({R.id.hm_close, R.id.hm_old_im, R.id.hm_new_im, R.id.hm_sub_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.hm_close:
                finish();
                break;
            case R.id.hm_old_im:
                hmNewIm.setChecked(false);
                isNew=false;
                break;
            case R.id.hm_new_im:
                hmOldIm.setChecked(false);
                isNew=true;
                break;
            case R.id.hm_sub_tv:
                subHttp();
                break;
        }
    }
    @Override
    protected void handleReceiver(Context context, Intent intent) {
        super.handleReceiver(context, intent);
        if (isVisible) {
            if (getString(R.string.SCAN_ACTION).equals(intent.getAction())) {
                String scanStatus = intent.getStringExtra(getString(R.string.SCAN_STATE));
                if ("ok".equals(scanStatus)) {
                    // 成功
                    String resultStr = intent.getStringExtra(getString(R.string.DATA_STRING)).trim()+"";
                    // 生成单元
                    if (!Utils.isEmpty(resultStr)){
                        if (isHave(resultStr)){
                            showToast("重复扫码！");
                            return;
                        }
                        if (!isNew){
                            hmOldEd.setText(resultStr+"");
                        }else {
                            hmNewEd.setText(resultStr+"");
                        }
                    }else {
                        showToast(getString(R.string.scan_timeout_warn), 0);
                    }
                }
            }
        }
    }
    @Override
    protected void handleIDataReceiver(Context context, Intent intent) {
        // TODO Auto-generated method stub
        super.handleIDataReceiver(context, intent);
        if (isVisible) {
//			String scanResult1 = intent.getStringExtra("value");
            if (getString(R.string.SCAN_IDATA_ACTION).equals(intent.getAction())) {
                String scanResult = intent.getStringExtra("value") + "";
                if (scanResult.contains("s.idcode.org.cn")) {
                    return;
                }
                if (!Utils.isEmpty(scanResult) && scanResult.length() > 0) {
                    if (isHave(scanResult)){
                        showToast("重复扫码！");
                        return;
                    }
                    // 生成单元
                    if (!isNew){
                        hmOldEd.setText(scanResult+"");
                    }else {
                        hmNewEd.setText(scanResult+"");
                    }
                }else {
                    showToast(getString(R.string.scan_timeout_warn), 0);
                }
            }
        }
    }

    private boolean isHave(String val) {
        if (!Utils.isEmpty(hmOldEd.getText().toString()+"")){
            hmOldEd.getText().toString().equals(val);
            return true;
        }
        if (!Utils.isEmpty(hmNewEd.getText().toString()+"")){
            hmNewEd.getText().toString().equals(val);
            return true;
        }
        return false;
    }

    private void subHttp() {
        ReplaceCodeRequest replaceCodeRequest=new ReplaceCodeRequest();
        replaceCodeRequest.setOldCode(hmOldEd.getText().toString()+"");
        replaceCodeRequest.setNewCode(hmNewEd.getText().toString()+"");
        replaceCodeRequest.setUserId(MyApplication.mSettings.getLong("personid",0));
        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title),
                getString(R.string.alert_message), true, false);
        HMReturnAsyn outStorageAsyn = new HMReturnAsyn();
        outStorageAsyn.execute(replaceCodeRequest);
    }
    /**
     * 换码
     *
     * @author tjh
     *
     */
    private class HMReturnAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();
            if (res == null || res.equals("")) {
                Toast.makeText(New_HM_Activity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    if(jo.getInt("code")!=200){
                        return;
                    }
                    New_HM_Activity.this.finish();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            ReplaceCodeRequest outStorageRequest = (ReplaceCodeRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.replaceCode),
                    outStorageRequest);
//            String res = Utils.getCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp)+
//                    "?codes="+outStorageRequest.getCodes()+"&personid="+outStorageRequest.getPersonid());
            return res;
        }
    }
}
